#ifndef __ILIB_UTIL_H_20120614__
#define __ILIB_UTIL_H_20120614__

#include "../../iHeader.h"

inline int32_t get_error_nbr()
{
#if defined(__WIN__)
    return GetLastError();
#elif defined(__LINUX__)
    return errno;
#endif
}
inline char* get_bin_path(char* path, uint32_t len)
{
    if(len <= 0)
        return NULL;

#if defined(__WIN__)
    int32_t count = GetModuleFileName(NULL, path, len);
#elif defined(__LINUX__)
    int32_t count = readlink( "/proc/self/exe", path, len); 
#endif
    if ( count < 0 || count >= len ) 
        return NULL;

    path[len] = 0;
    return path;
}
inline char* get_bin_dir(char* dir, uint32_t len)
{
#if defined(__WIN__)
    const char SEP = '\\';
#elif defined(__LINUX__)
    const char SEP = '/';
#endif
    if(NULL == get_bin_path(dir,len))
        return NULL;

    char* p = dir+strlen(dir);
    while(*p != SEP)
        *p-- = 0;


    if(p!=dir)
        *p = 0;

    return dir;
}
inline char* strupr(char* src)
{
    if(NULL==src)
        return NULL;

    char* p = src;
    while(*p)
    {
        *p = toupper(*p);
        ++p;
    }

    return src;
}
inline char* tolwr(char* src)
{
    if(NULL==src)
        return NULL;
    char* p = src;
    while(*p)
    {
        *p = tolower(*p);
        ++p;
    }
    return src;
}
inline bool parse_address(const char* src, char proto[32], char ip[64], char port[8])
{
    if(NULL == src) 
        return false;
   
    // retreives PROTOCOL
    char* s = (char*)src;
    char* e = strchr(s, ':');
    if(NULL == e)
        return false;
    if((e-s) > 31)
        return false;
    strncpy(proto, s, e-s);
    proto[e-s] = 0;
    strupr(proto);

    if(*++e!='/' || *++e!='/')
        return false;
    s=++e;
   
    // reteives IP
    e = strchr(s, ':');
    if(NULL==e)
        return false;
    if((e-s) > 63)
        return false;
    strncpy(ip, s, e-s);
    ip[e-s] = 0;

    // retreives PORT
    s = ++e;
    if(*e==0)
        return false;
    while(*++e){}
    if((e-s) > 7)
        return false;
    strncpy(port, s, e-s);
    port[e-s] = 0;
    return true;
}

#endif // __ILIB_UTIL_H_20120614__

